<template>
    <div>
        <app-search>
            <el-form :model="company" :label-position="$store.labelPosition"
                     label-width="20%" ref="company" :rules="rules">
                <el-row>
                    <el-col :span="18">
                        <el-form-item label="公司名称：" prop="name">
                            <el-input v-model="company.name" :disabled="isView"></el-input>
                        </el-form-item>

                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="18">
                        <el-form-item label="地区：" prop="detailArea">
                            <el-cascader :disabled="isView"
                                :options="addressOptions"
                                v-model="selectedAddresses"
                                @change="handleChangeAddress">
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="18">
                        <el-form-item label="地址：" prop="address">
                            <el-input v-model="company.address" :disabled="isView"></el-input>
                        </el-form-item>

                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="18">
                        <el-form-item label="公司电话：" prop="phone">
                            <el-input v-model="company.phone" :disabled="isView"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="18">
                        <el-form-item label="公司邮箱：" prop="email">
                            <el-input v-model="company.email" :disabled="isView"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-if="isSupplyCompany">
                    <el-col :span="18">
                        <el-form-item label="开户行：" prop="bank">
                            <el-input v-model="company.bank" :disabled="isView"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="isSupplyCompany">
                    <el-col :span="18">
                        <el-form-item label="银行帐号：" prop="account">
                            <el-input v-model="company.account" :disabled="isView"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="isSupplyCompany">
                    <el-col :span="18">
                        <el-form-item label="供应商类别：" prop="supplyType">
                            <el-select v-model="company.supplyType" clearable
                                       placeholder="请选择" style="width: 100%;" :disabled="isView">
                                <el-option v-for="st in supplyTypes" :key="st.code"
                                           :label="st.description" :value="st.code">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="isSupplyCompany">
                    <el-col :span="18">
                        <el-form-item label="供应商级别：" prop="supplyGrade">
                            <el-select v-model="company.supplyGrade" clearable
                                       placeholder="请选择" style="width: 100%;" :disabled="isView">
                                <el-option v-for="st in supplyGrades" :key="st.code"
                                           :label="st.description" :value="st.code">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row >
                    <el-col :span="18">
                        <el-form-item >
                            <el-button type="edit" icon="fa fa-save" @click="submitForm()" v-if="!isView">
                                保存
                            </el-button>

                            <el-button type="edit" icon="el-icon-plus" v-if="!isView && isEditCompany"
                                       @click="showAddContact()">添加联系人</el-button>
                            <el-button type="danger" icon="el-icon-delete" v-if="!isView && isEditCompany"
                                       @click="deleteContacts()">删除联系人</el-button>

                            <el-button type="primary" icon="el-icon-back" @click="cancel()">
                                返回
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </app-search>

        <template v-if="isEditCompany">
        <contact-list v-bind:tableData="contacts"></contact-list>

        <contact-edit v-bind:contact="contact"></contact-edit>
        </template>

    </div>

</template>

<script>
import ContactEdit from './contact_edit';
import ContactList from './contact_list';
import { mapState } from 'vuex';

import { regionData,  CodeToText, TextToCode } from 'element-china-area-data';

export default {
    name: "CompanyEdit",
    components: {ContactList, ContactEdit},
    data() {
        return {
            addressOptions: regionData,
            selectedAddresses: [],
            company: {},
            rules:{
                name:[{ required: true, message: '请输入公司名称', trigger: ['blur'] }],
                address:[{ required: true, message: '请输入公司地址', trigger: ['blur'] }],
                email:[{ type: 'email', message: '无效的邮箱', trigger: ['blur'] }],
            }
        }
    },
    mounted() {
        console.log("isView: ", this.$store.isView)
        this.initCompany()
    },

    methods: {
        handleChangeAddress (value) {
            console.log("handleChangeAddress values: ", value)
            this.company.province = CodeToText[this.selectedAddresses[0]];
            this.company.city = CodeToText[this.selectedAddresses[1]];
            this.company.district = CodeToText[this.selectedAddresses[2]];
            console.log(this.company.province, this.company.city, this.company.district)
        },
        // 获取公司数据
        async initCompany() {
            console.log("companyId=", this.companyId);
            let res = await this.$axios.get(`/company/${this.companyId}`);
            console.log("返回的公司信息：", res);
            this.company = res.result.company;

            if(this.company.province){
                // 把地址转换成代码
                let province = TextToCode[this.company.province];
                let addresses = [];
                addresses.push(province.code);
                let city = province[this.company.city];
                console.log("city: ", city.code)
                addresses.push(city.code);
                addresses.push(city[this.company.district].code);
                console.log("address: ", addresses)
                this.selectedAddresses = addresses;
            }else{
                this.selectedAddresses = []
            }

            this.$store.commit("company/Set_Contacts", res.result.contacts);
        },

        showAddContact(){
            this.$store.commit("company/Show_Add_Contact")
        },

        submitForm(){
            this.$refs['company'].validate((valid) => {
                if(valid){
                    this.saveCompany();
                }
            });
        },

        async saveCompany(){
            this.company.ctype = this.ctype;
            if(this.isEditCompany){
                await this.$axios.put('/company', this.company);
                this.$myMsg.success('成功修改公司信息。');
            }else{
                let res = await this.$axios.post('/company', this.company);
                this.$myMsg.success('成功创建公司信息。请增加公司项信息。');
                console.log("创建公司后返回：", res);
                this.$store.dispatch('company/showEditCompany', res.result);
                this.initCompany();
            }
        },

        deleteContacts(){
            if(this.selectedContacts.length === 0){
                this.$myMsg.warning("请选择要删除的联系人")
                return;
            }

            this.$confirm('确实要删除选中的联系人吗？', '确认信息', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            })
            .then(() => {
                this.actualDeleteContacts();
            })
            .catch(action => {
                this.$myMsg.info('已放弃删除选中的联系人。');
            });
        },

        async actualDeleteContacts(){
            let deletedIds = "";
            this.selectedContacts.forEach( item => {
                deletedIds += item.id + ",";
            });

            await this.$axios.delete(`/contact/batchRemove/${deletedIds}`);
            this.$myMsg.success('删除成功');
            this.$store.dispatch("company/removeContacts");
        },

        cancel(){
            this.$store.commit("company/Set_Show_Edit_Company", false);
        }

    },

    computed: {
        ...mapState({
            supplyGrades: state => state.company.initPageData.supplyGrades,
            supplyTypes: state => state.company.initPageData.supplyTypes,
            companyId: state => state.company.companyId,
            contact: state => state.company.contact,
            contacts: state => state.company.contacts,
            selectedContacts: state => state.company.selectedContacts,
            isView: state => state.company.isView,
            ctype: state => state.company.ctype
        }),

        isEditCompany(){
            return this.companyId > -1
        },

        isSupplyCompany(){
            return this.ctype === 2
        }
    }
}
</script>

